package com.dankegongyu.demo.http.http;

import com.dankegongyu.lib.http.utils.DKHttpLogUtils;
import com.dankegongyu.lib.http.utils.GsonUtil;

import java.io.IOException;

import io.reactivex.annotations.NonNull;
import io.reactivex.observers.DisposableObserver;
import retrofit2.HttpException;

/**
 * @author wpq
 * @version 1.0
 */
public abstract class DKObserver<T> extends DisposableObserver<T> {

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onError(@NonNull Throwable e) {
//        DKLog.e(" -> " + e.toString());
        onFinish();

        HttpError httpError = null;
        if (e instanceof HttpException) {
            HttpException exception = (HttpException) e;
            try {
                //noinspection ConstantConditions
                httpError = GsonUtil.fromJson(exception.response().errorBody().string(), HttpError.class);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } else {
            httpError = GsonUtil.fromJson(e.getLocalizedMessage(), HttpError.class);
        }

        if (httpError == null) {
            httpError = new HttpError();
            httpError.description = "请求失败";
        }

        // 特殊错误拦截
//        if (!BusinessService.handleBusinessCode(httpError.businessCode)) {
            onError(httpError);
//        }
    }

    protected void onError(@NonNull HttpError httpError) {
        DKHttpLogUtils.e(httpError.description);
    }

    @Override
    public void onComplete() {
//        QLKLog.e("onComplete");
        onFinish();
    }

    protected void onFinish() {

    }

}
